const router = require('koa-router')()
const { formidable } = require('formidable');
const path = require('path')
//仓库管理模块
router.prefix('/goods')
//1.增加产品/原料
router.post('/', async (ctx, next) => {
    let form = formidable({
        uploadDir: path.resolve(__dirname, '../public/goods'),
        //是否保留扩展名
        keepExtensions: true,
        //将文件作为数组出现
        multiples: true
    })
    form.parse(ctx.req, async (err, fields, files) => {
        if (err) {
            console.log(err)
        } else {
            let name = JSON.parse(fields.data).goods_name;
            let src = 'http://localhost:3000/goods/' + files.image[0].newFilename;
            let type = JSON.parse(fields.data).goods_type;
            if (type == "原料") {
                type = "material";
            } else {
                type = "product";
            }
            let num = JSON.parse(fields.data).goods_num;
            let sql = "insert into goods (goods_name, goods_pic,goods_type, goods_num) values('" + name + "', '" + src + "', '" + type + "','" + num + "')";
            await ctx.db.EXCUTE(sql, []);
        }
    })
    ctx.body = {
        "status": 200,
        "msg": '添加成功',
    }
})

//2.盘库--修改数量
router.put('/', async (ctx, next) => {
    let num = ctx.request.body.num;
    let id = ctx.request.body.goodsId;
    let sql = `update goods set goods_num = '${num}' WHERE goods_id = ${id}`;
    await ctx.db.EXCUTE(sql, []);
    let obj = {
        msg: "编辑成功",
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//3.查找产品
router.get('/', async (ctx, next) => {
    if (ctx.request.query.name) {
        let name = ctx.request.query.name;
        let countSql = `select count(*) from goods where goods_name like '%${name}%'`;
        let countResults = await ctx.db.EXCUTE(countSql, []);
        let total = countResults[0]["count(*)"];
        let pageSize = Number(ctx.request.query.size)
        let page = ctx.request.query.page
        let startRow = total > 0 ? ((page - 1) * pageSize) : 0;
        //实现分页限制查找
        let limitSql = `select * from goods where goods_name like '%${name}%' order by goods_id desc limit ${startRow},${pageSize}`;
        let results = await ctx.db.EXCUTE(limitSql, []);
        let obj = {
            length: total,
            results: results,
            status: 200
        }
        ctx.body = JSON.stringify(obj);
    } else if (ctx.request.query.type) {
        let type = "";
        if (ctx.request.query.type == "产品") {
            type = "product";
        } else {
            type = "material";
        }
        let countSql = `select count(*) from goods where goods_type='${type}'`;
        let countResults = await ctx.db.EXCUTE(countSql, []);
        let total = countResults[0]["count(*)"];
        let pageSize = Number(ctx.request.query.size)
        let page = ctx.request.query.page
        let startRow = total > 0 ? ((page - 1) * pageSize) : 0;
        //实现分页限制查找
        let limitSql = `select * from goods where goods_type='${type}' order by goods_id desc limit ${startRow},${pageSize}`;
        let results = await ctx.db.EXCUTE(limitSql, []);
        let obj = {
            length: total,
            results: results,
            status: 200
        }
        ctx.body = JSON.stringify(obj);
    }
    else if (ctx.request.query.name && ctx.request.query.type) {
        let type = "";
        if (ctx.request.query.type == "产品") {
            type = "product";
        } else {
            type = "material";
        }
        let name = ctx.request.query.name;
        let countSql = `select count(*) from goods where goods_name like '%${name}%' and goods_type='${type}'`;
        let countResults = await ctx.db.EXCUTE(countSql, []);
        let total = countResults[0]["count(*)"];
        let pageSize = Number(ctx.request.query.size)
        let page = ctx.request.query.page
        let startRow = total > 0 ? ((page - 1) * pageSize) : 0;
        //实现分页限制查找
        let limitSql = `select * from goods where goods_name like '%${name}%' and goods_type='${type}' order by goods_id desc limit ${startRow},${pageSize}`;
        let results = await ctx.db.EXCUTE(limitSql, []);
        let obj = {
            length: total,
            results: results,
            status: 200
        }
        ctx.body = JSON.stringify(obj);
    } else {
        let countSql = "select count(*) from goods";
        let countResults = await ctx.db.EXCUTE(countSql, []);
        let total = countResults[0]["count(*)"];
        let pageSize = Number(ctx.request.query.size)
        let page = ctx.request.query.page
        let startRow = total > 0 ? ((page - 1) * pageSize) : 0;
        //实现分页限制查找
        let limitSql = `select * from goods order by goods_id desc limit ${startRow},${pageSize}`;
        let results = await ctx.db.EXCUTE(limitSql, []);
        let obj = {
            length: total,
            results: results,
            status: 200
        }
        ctx.body = JSON.stringify(obj);
    }
})

//4.删除产品
router.delete('/', async (ctx, next) => {
    let sql = `delete from goods where goods_id=${ctx.request.body.goodsId}`
    let results = await ctx.db.EXCUTE(sql, []);
    if (results.affectedRows > 0) {
        let obj = {
            status: 200,
            msg: '删除成功'
        }
        ctx.body = JSON.stringify(obj);
    }
})

//5.获取出库/入库请求列表
router.get('/require', async (ctx, next) => {
    //requireName=出库/入库
    let requireName = ctx.request.query.requireName;
    let countSql = `select count(*) from requires where require_kind like '%${requireName}%'`;
    let countResults = await ctx.db.EXCUTE(countSql, []);
    let total = countResults[0]["count(*)"];
    let pageSize = Number(ctx.request.query.size)
    let page = ctx.request.query.page
    let startRow = total > 0 ? ((page - 1) * pageSize) : 0;
    //实现分页限制查找
    let limitSql = `select * from requires where require_kind like '%${requireName}%' order by require_id desc limit ${startRow},${pageSize}`;
    let results = await ctx.db.EXCUTE(limitSql, []);
    let obj = {
        length: total,
        results: results,
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})

//6.批准入库申请
router.post('/inRequire', async (ctx, next) => {
    let id = ctx.request.body.requireId;
    let sql = `select require_kind,require_orid,require_detail from requires where require_id = '${id}'`;
    let result = await ctx.db.EXCUTE(sql, []);
    let kind = result[0].require_kind;
    let orid = result[0].require_orid;
    let detail = result[0].require_detail;
    let detailArray = detail.split("||");
    //入库
    //数据库+
    for (var i = 0; i < detailArray.length; i++) {
        if (i % 2 == 1) {
            let mt = detailArray[i - 1];
            let num = Number(detailArray[i]);
            let sql = `select goods_num from goods where goods_name = '${mt}'`;
            let result = await ctx.db.EXCUTE(sql, []);
            let num1 = result[0].goods_num;
            let num2 = num1 + num;
            let sql1 = `update goods set goods_num = ${num2} where goods_name = '${mt}'`;
            await ctx.db.EXCUTE(sql1, []);
        }
    }
    if (kind == "原料入库") {
        //改状态
        let sql3 = `update buy set buy_type = '已完成' WHERE buy_id = ${orid}`;
        let sql4 = `update requires set require_type = '已完成' WHERE require_id = ${id}`;
        await ctx.db.EXCUTE(sql3, []);
        await ctx.db.EXCUTE(sql4, []);
    }
    if (kind == "产品入库") {
        //改状态
        let sql3 = `update requires set require_type = '已完成' WHERE require_id = ${id}`;//请求状态已完成
        let sql4 = `update produce set product_type = '待出库' WHERE product_id = ${orid}`;//生产状态已完成
        let sql5 = `select product_orderid from produce where product_id = '${orid}'`;
        let results = await ctx.db.EXCUTE(sql5, []);
        let orderid = results[0].product_orderid;
        let sql6 = `update orders set order_type = '生产完成,待出库' WHERE order_id = ${orderid}`;//订单状态已完成
        await ctx.db.EXCUTE(sql3, []);
        await ctx.db.EXCUTE(sql4, []);
        await ctx.db.EXCUTE(sql6, []);
    }

    let obj = {
        status: 200,
        msg: '入库成功'
    }
    ctx.body = JSON.stringify(obj);
})

//7.批准提库申请
router.post('/outRequire', async (ctx, next) => {
    let id = ctx.request.body.requireId;
    let sql = `select require_kind,require_orid,require_detail from requires where require_id = '${id}'`;
    let result = await ctx.db.EXCUTE(sql, []);
    let kind = result[0].require_kind;
    let orid = result[0].require_orid;
    let detail = result[0].require_detail;
    let detailArray = detail.split("||");
    //出库
    //数据库-
    for (var i = 0; i < detailArray.length; i++) {
        if (i % 2 == 1) {
            let mt = detailArray[i - 1];
            let num = Number(detailArray[i]);
            let sql = `select goods_num from goods where goods_name = '${mt}'`;
            let result = await ctx.db.EXCUTE(sql, []);
            let num1 = result[0].goods_num;
            let num2 = num1 - num;
            let sql1 = `update goods set goods_num = ${num2} where goods_name = '${mt}'`;
            await ctx.db.EXCUTE(sql1, []);
        }
    }
    if (kind == "原料出库") {
        //改状态
        let sql3 = `update produce set product_type = '生产中' WHERE product_id = ${orid}`;
        let sql4 = `update requires set require_type = '已完成' WHERE require_id = ${id}`;
        await ctx.db.EXCUTE(sql3, []);
        await ctx.db.EXCUTE(sql4, []);
    }
    if (kind == "产品出库") {
        //改状态
        let sql3 = `update produce set product_type = '已完成' WHERE product_orderid = ${orid}`;
        let sql4 = `update requires set require_type = '已完成' WHERE require_id = ${id}`;
        // let sql5 = `select product_orderid from produce where product_id = '${orid}'`;
        // let results = await ctx.db.EXCUTE(sql5, []);
        // let orderid = results[0].product_orderid;
        let sql6 = `update orders set order_type = '已完成' WHERE order_id = ${orid}`;//订单状态已完成
        await ctx.db.EXCUTE(sql3, []);
        await ctx.db.EXCUTE(sql4, []);
        await ctx.db.EXCUTE(sql6, []);
    }
    let obj = {
        status: 200,
        msg: '处理成功'
    }
    ctx.body = JSON.stringify(obj);
})

module.exports = router